<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="86px"
    >
      <!-- <el-form-item label="目录id" prop="cateId">
        <el-input
          v-model="queryParams.cateId"
          placeholder="请输入目录id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源id" prop="dsId">
        <el-input
          v-model="queryParams.dsId"
          placeholder="请输入数据源id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="数据表名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入数据表名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属单位" prop="tenantId">
        <el-input
          v-model="queryParams.tenantId"
          placeholder="请输入所属单位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表注释" prop="comment">
        <el-input
          v-model="queryParams.comment"
          placeholder="请输入表注释"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddTb"
          v-hasPermi="['web:data:query:sdkDqThemeTb:add']"
        >
          新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate({})"
          v-hasPermi="['web:data:query:sdkDqDsTb:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete({})"
          v-hasPermi="['web:data:query:sdkDqDsTb:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['web:data:query:sdkDqDsTb:import']"
        >
          导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['web:data:query:sdkDqDsTb:export']"
        >
          导出
        </el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <!-- <el-table-column label="目录id" align="center" prop="cateId" />
      <el-table-column label="数据源id" align="center" prop="dsId" /> -->
      <el-table-column label="所属单位" align="center" prop="tenantId" />
      <el-table-column label="数据表名称" align="center" prop="name" />
      <el-table-column label="表注释" align="center" prop="comment" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['web:data:query:sdkDqDsTb:edit']"
          >
            修改
          </el-button> -->
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['web:data:query:sdkDqThemeTb:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="aTitle"
      v-model="aOpen"
      width="1100px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="aFormRef" :model="aForm">
          <el-form-item label="所属节点">
            <el-input v-model="selectPNode.label" disabled />
          </el-form-item>
          <el-form-item label="类型">
            <span>表</span>
          </el-form-item>
          <el-form-item label="所属库">
            <el-select v-model="aForm.dsId" @change="handeDsChange">
              <el-option
                v-for="(ds, index) in dsList"
                :key="index"
                :label="ds.name"
                :value="ds.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="p-3">
        <el-table :data="aData" :loading="aLoading" @selection-change="handleSelectionAChange">
          <el-table-column type="selection" width="55" align="center" />

          <el-table-column label="表注释" prop="comment" />
          <el-table-column label="表名称" prop="name" />
          <el-table-column label="表ID" prop="id" />
        </el-table>
        <pagination
          v-show="aTotal > 0"
          :total="aTotal"
          v-model:page="apageParams.pageNum"
          v-model:limit="apageParams.pageSize"
          @pagination="getNoThemeList"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAForm">确 定</el-button>
          <el-button @click="aCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="title"
      v-model="open"
      width="1100px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        class="grid grid-cols-2 gap-2"
        label-width="96px"
      >
        <!-- <el-form-item label="目录id" prop="cateId">
          <el-input v-model="form.cateId" placeholder="请输入目录id" />
        </el-form-item>
        <el-form-item label="数据源id" prop="dsId">
          <el-input v-model="form.dsId" placeholder="请输入数据源id" />
        </el-form-item> -->

        <el-form-item label="数据表名称" prop="name">
          <el-input v-model="form.name" :disabled="isEdit" placeholder="请输入数据表名称" />
        </el-form-item>
        <el-form-item label="所属单位" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入所属单位" />
        </el-form-item>
        <el-form-item label="表注释" prop="comment">
          <el-input v-model="form.comment" placeholder="请输入表注释" />
        </el-form-item>
      </el-form>
      <div>
        <div class="mb-3">
          <el-button type="primary" :disabled="isEdit" icon="Plus" plain @click="handledAddFiled"
            >新增字段</el-button
          >
        </div>
        <vxe-table
          ref="tableRef"
          border
          :data="form.sdkDqDsTbCls"
          :loading="colLoading"
          :edit-rules="validRules"
          keep-source
          :edit-config="{ trigger: 'manual', mode: 'row', autoClear: false, showStatus: true }"
        >
          <vxe-column field="name" title="字段名" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.name" />
            </template>
          </vxe-column>
          <vxe-column field="type" title="字段类型" :edit-render="{}">
            <template #default="{ row }">
              {{ formatFieldType(row, { property: 'type' }) }}
            </template>
            <template #edit="{ row }">
              <el-select v-model="row.type">
                <el-option
                  v-for="(item, index) in fieldOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.jdbcType"
                />
              </el-select>
            </template>
          </vxe-column>
          <vxe-column field="formJavaType" title="表单java类型" :edit-render="{}">
            <template #default="{ row }">
              {{ formatFieldJavaType(row, { property: 'formJavaType' }) }}
            </template>
            <template #edit="{ row }">
              <el-select v-model="row.formJavaType">
                <el-option
                  v-for="(item, index) in fieldJavaOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </vxe-column>
          <vxe-column field="length" title="字段长度" :edit-render="{}">
            <template #edit="{ row }">
              <div class="w-full">
                <el-input-number
                  style="width: 100%"
                  :controls="false"
                  v-model="row.length"
                  :precision="0"
                  :min="1"
                />
              </div>
            </template>
          </vxe-column>
          <vxe-column field="decimalLength" title="字段精度" :edit-render="{}">
            <template #edit="{ row }">
              <div class="w-full">
                <el-input-number
                  style="width: 100%"
                  :controls="false"
                  v-model="row.decimalLength"
                  :precision="0"
                  :min="0"
                />
              </div>
            </template>
          </vxe-column>
          <vxe-column field="ableBeNull" title="允许Null" :edit-render="{}">
            <template #default="{ row }">
              {{ ableBeNullOptions.find((item) => item.value === row.ableBeNull)?.label }}
            </template>
            <template #edit="{ row }">
              <el-select v-model="row.ableBeNull">
                <el-option
                  v-for="(item, index) in ableBeNullOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </vxe-column>
          <vxe-column field="comment" title="字段注释" :edit-render="{ name: 'VxeInput' }">
            <template #edit="{ row }">
              <vxe-input v-model="row.comment" />
            </template>
          </vxe-column>
          <vxe-column title="操作">
            <template #default="{ row }">
              <template v-if="isEditStatus(row)">
                <el-button link style="color: #409eff" @click="saveRowEvent(row)">保存</el-button>
                <el-button link @click="cancelRowEvent(row)">取消</el-button>
              </template>
              <template v-else>
                <el-button link style="color: #409eff" @click="editRowEvent(row)">编辑</el-button>
                <el-button link style="color: red" @click="removeRowEvent(row)">删除</el-button>
              </template>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的数据查询-数据表表数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, watch, computed } from 'vue';
  import {
    pageSdkDqDsTb,
    addSdkDqDsTb,
    updateSdkDqDsTb,
    tplSdkDqDsTb,
  } from '@/api/web/db/dataquery/sdkDqDsTb';
  import { getToken } from '@/utils/auth';
  import { listSdkDqDs } from '@/api/web/db/dataquery/sdkDqDs';
  import { addBatchSdkDqThemeTb, delSdkDqThemeTb } from '@/api/web/db/dataquery/sdkDqThemeTb';
  // import { parseTime, addFieldTimeRange, addFieldDateRange } from '@/utils/base';
  // import { useDict, useConstDict } from '@/utils/dict';
  import modal from '@/plugins/modal';

  import { useFieldOptions } from './useConstant';

  const { fieldOptions, fieldJavaOptions, formatFieldType, formatFieldJavaType } =
    useFieldOptions();

  const props = defineProps({
    selectPNode: {
      type: Object,
      default: () => ({}),
    },
  });

  const emit = defineEmits(['refresh']);
  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({
    cateId: null,
    dsId: null,
    tenantId: null,
    name: null,
    comment: null,
  });
  const queryRef = ref(null);
  const list = ref([]);
  const open = ref(false);
  const loading = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');
  const isEdit = ref(false);
  const colLoading = ref(false);
  const tableRef = ref(null);

  const uploadRef = ref(null);
  const upload = ref({
    open: false,
    title: '',
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: 'Bearer ' + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + '/web/data/query/sdkDqDsTb/import',
  });

  const formRef = ref(null);
  const form = ref({});
  const rules = ref({
    tenantId: [
      {
        min: 0,
        max: 64,
        message: '所属单位长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
    name: [
      { required: true, message: '数据表名称必填' },
      {
        min: 0,
        max: 64,
        message: '数据表名称长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
    comment: [
      {
        min: 0,
        max: 64,
        message: '表注释长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
  });

  const validRules = {
    name: [{ required: true, message: '请输入字段名称' }],
  };

  const isEditStatus = computed(() => (row) => {
    const $table = tableRef.value;
    if ($table) {
      return $table.isEditByRow(row);
    }
    return false;
  });
  const ableBeNullOptions = ref([
    { label: '允许', value: true },
    { label: '不允许', value: false },
  ]);
  // const fieldOptions = ref([]);

  const aFormRef = ref(null);
  const aOpen = ref(false);
  const aTitle = ref('');
  const aData = ref([]);
  const aLoading = ref(false);
  const apageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const aTotal = ref(0);
  const aForm = ref({
    dsId: null,
  });
  const dsList = ref([]);
  const selectionItems = ref([]);

  watch(
    () => props.selectPNode,
    (pnode) => {
      if (pnode) {
        // queryParams.value.cateId = pnode.pid;
        queryParams.value.themeId = pnode.id;

        getList();

        // getFormColTypeOption();
      }
    },
    { immediate: true },
  );

  // 新增 按钮
  async function handleAddTb() {
    aReset();
    aTitle.value = '新增子项';
    await getNoThemeList();
    getdsAll();
    aOpen.value = true;
  }
  // 数据库列表
  async function getdsAll() {
    const res = await listSdkDqDs().catch(() => {});
    console.log({ res });
    dsList.value = res?.data || [];
    return Promise.resolve();
  }
  // 未选择主题的表
  async function getNoThemeList() {
    aLoading.value = true;
    console.log({ queryParams: queryParams.value });
    const res = await pageSdkDqDsTb(apageParams.value, {
      ...aForm.value,
      notThemeId: props.selectPNode.id,
    })
      .catch(() => {})
      .finally(() => {
        aLoading.value = false;
      });

    aData.value = res?.data?.records ?? [];
    aTotal.value = res?.data?.total ?? 0;
    console.log({ aData: aData.value });
    return Promise.resolve();
  }
  // 弹窗中选主题 change
  function handleSelectionAChange(selection) {
    console.log({ selection });
    selectionItems.value = selection.map((item) => {
      return {
        pid: props.selectPNode.id,
        tbId: item.id,
      };
    });
  }
  // 弹窗中 库 change
  function handeDsChange() {
    apageParams.value.pageNum = 1;
    selectionItems.value = [];
    getNoThemeList();
  }
  // 弹窗中的确定按钮
  async function submitAForm() {
    if (!selectionItems.value.length) {
      modal.msgWarning('请选择关联主题的表数据');
      return;
    }
    const res = await addBatchSdkDqThemeTb(selectionItems.value).catch(() => {});
    console.log({ res });
    aOpen.value = false;
    selectionItems.value = [];
    aTotal.value = 0;
    emit('refresh');
    pageParams.value.pageNum = 1;
    getList();
  }
  // 弹窗中的取消按钮
  function aCancel() {
    aOpen.value = false;
    aReset();
  }
  function aReset() {
    apageParams.value.pageNum = 1;
    selectionItems.value = [];
    aData.value = [];
    aTotal.value = 0;
    aForm.value = {
      dsId: null,
    };
    aFormRef.value?.resetFields();
  }

  function handleDelete(row) {
    const _ids = row?.id;
    modal
      .confirm('是否确认删除数据查询-数据主题关联表表编号为"' + _ids + '"的数据项？')
      .then(() => {
        const params = {
          pid: props.selectPNode.id,
          tbId: _ids,
        };
        console.log({ params });
        return delSdkDqThemeTb(params);
      })
      .then(() => {
        getList();
        emit('refresh');
        modal.msgSuccess('删除成功');
      })
      .catch(() => {});
  }

  async function removeRowEvent(row) {
    const $table = tableRef.value;
    if ($table) {
      const type = await modal.confirm('您确定要删除该数据?');
      if (type === 'confirm') {
        $table.remove(row);
      }
    }
  }

  async function saveRowEvent(row) {
    const $table = tableRef.value;
    if ($table) {
      const errMap = await $table.validate();
      if (errMap) {
        return;
      }
      await $table.clearEdit();
      // 重新加载行
      console.log({ row });
      await $table.reloadRow(row, {});

      console.log(1, $table.isEditByRow(row));
      // modal.msgSuccess('success');
    }
  }
  async function cancelRowEvent(row) {
    const $table = tableRef.value;
    if ($table) {
      const errMap = await $table.validate();
      if (errMap) {
        $table.remove(row);
        return;
      }
      console.log({ row });
      await $table.clearEdit();
      // 还原数据
      await $table.revertData(row);
    }
  }
  async function editRowEvent(row) {
    const $table = tableRef.value;
    if ($table) {
      const errMap = await $table.validate();
      if (errMap) {
        return;
      }
      await $table.setEditRow(row);
    }
  }

  function vaildFieldTable() {
    const $table = tableRef.value;
    if ($table) {
      const data = $table.getEditRecord();
      console.log({ data });
      return !!data;
      // if(data){
      //   modal.msgWarning('请保存数据')
      // }
    }
  }

  function getList() {
    loading.value = true;
    console.log({ queryParams: queryParams.value });
    pageSdkDqDsTb(pageParams.value, queryParams.value)
      .then((res) => {
        list.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function cancel() {
    open.value = false;
    reset();
  }

  function reset() {
    form.value = {
      id: null,
      cateId: props.selectPNode.pid,
      dsId: props.selectPNode.id,
      tenantId: null,
      name: null,
      comment: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      sdkDqDsTbCls: [],
    };
    formRef.value?.resetFields();
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }
  const obj = {
    cateId: null,
    dsId: null,
    tbId: null,
    tenantId: null,
    name: null,
    comment: null,
    pk: null,
    pkType: null,
    ableBeNull: null,
    defaultShow: null,
    desensitizer: null,
    type: null,
    length: null,
    decimalLength: null,
    defaultValue: null,
    formJavaType: null,
    inputType: null,
    dictType: null,
    sortValue: null,
  };
  async function handledAddFiled() {
    const $table = tableRef.value;

    if ($table) {
      const errMap = await $table.validate();
      if (errMap) {
        return;
      }
      const record = {
        ...obj,
      };
      const { row: newRow } = await $table.insertAt(record);
      if (!$table.isEditByRow(newRow)) {
        $table.setEditRow(newRow);
      }
      // await $table.setEditCell(newRow, 'name')
    }
    // tableRef.value.unshift(obj)
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        const params = { ...form.value };
        const hasEditRow = vaildFieldTable();
        if (hasEditRow) {
          modal.msgWarning('请保存数据');
          return;
        } else {
          console.log({
            form: form.value,
            data: tableRef.value.getData(),
            tdata: tableRef.value.getTableData().tableData,
          });
          params.sdkDqDsTbCls = tableRef.value.getTableData().tableData.map((item) => {
            return {
              ...item,
              cateId: form.value.cateId,
              dsId: form.value.dsId,
              tbId: form.value.id,
            };
          });
          tableRef.value.getTableData().tableData.map((item) => {
            console.log({ item, name: item.name, vit: item.value });
          });
          console.log({ params });
        }
        if (params.id) {
          updateSdkDqDsTb(params).then(() => {
            modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addSdkDqDsTb(params).then(() => {
            modal.msgSuccess('新增成功');
            open.value = false;
            // getList();
            emit('refresh');
          });
        }
      }
    });
  }

  function importTemplate() {
    tplSdkDqDsTb();
  }

  function handleFileUploadProgress() {
    upload.value.isUploading = true;
  }

  function handleFileSuccess(res, file) {
    upload.value.open = false;
    upload.value.isUploading = false;
    uploadRef.value.handleRemove(file);
    modal.msgSuccess(res.msg);
    getList();
  }

  function submitFileForm() {
    uploadRef.value.submit();
  }

  // getList();
</script>
